<template>
  <div :class="$style.upload">
    <Button type="primary" :disabled="$attrs.disabled" @click="visible=true">{{ text }}</Button>
    <el-dialog
      :close-on-click-modal="false"
      :destroy-on-close="destroy"
      :visible.sync="visible"
      :title="title"
      :append-to-body="true"
      @close="resetHandle"
    >
      <Upload ref="upload" :exist-file-list="existFileList" :on-preview="previewHandle" v-bind="$attrs" />
    </el-dialog>
    <PreviewImage v-model="previewShow" :image-list="imageList" />
  </div>
</template>
<script>
import Upload from '@/components/uploadManual'
import Button from '@/components/Button'
import PreviewImage from '@/components/PreviewImage'
export default {
  name: 'DialogUpload',
  components: {
    Upload,
    Button,
    PreviewImage
  },
  inheritAttrs: false,
  props: {
    // 已上传的文件
    existFileList: {
      type: Array,
      default: () => ([])
    },
    title: {
      type: [Number, String],
      default: '上传附件'
    },
    text: {
      type: [Number, String],
      default: '上传附件'
    },
    destroy: {
      type: Boolean,
      default: true
    },
    clearFileList: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      visible: false,
      imageList: [],
      previewShow: false
    }
  },
  methods: {
    // 是图片
    isImage(file) {
      // FIXME:根据实际情况修改
      return /(png$)|(jpg$)|(gif$)|(jpeg$)|(bmp$)/.test(file.url)
    },
    // 不是图片直接查看
    openFile(file) {
      const a = document.createElement('a')
      // FIXME: 根据实际情况修改
      a.href = file.url
      a.download = file.name
      a.target = '_bank'
      a.click()
    },
    // 预览
    previewHandle(file, fileList) {
      if (this.isImage(file)) {
        this.imageList = fileList.filter(e => {
          return this.isImage(e)
        })
        this.previewShow = true
      } else {
        if (Object.keys(file).indexOf('url') === -1) {
          // file.url = URL.createObjectURL(file.raw)
          file.url = `/img/${file.filePath}`
        }
        this.openFile(file)
      }
    },
    resetHandle() {
      this.imageList = []
      this.previewShow = false
    },
    // 清空已上传的文件列表
    clearUploadedImage() {
      if (this.clearFileList) {
        if (this.$refs['upload']) this.$refs['upload'].clearFiles()
      }
    }
  }
}
</script>
<style lang="scss" module>
.upload{
    display: inline-block;
}
</style>
